package com.vcourse.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vcourse.cloud.oss.api.feign.OssService;
import com.vcourse.commons.result.R;
import com.vcourse.commons.utils.PageUtils;
import com.vcourse.service.base.dto.CourseDto;
import com.vcourse.service.edu.entity.*;
import com.vcourse.service.edu.mapper.*;
import com.vcourse.service.edu.service.CourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vcourse.service.edu.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Zengsh123
 * @since 2020-05-25
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Resource
    private CourseDescriptionMapper courseDescriptionMapper;
    @Resource
    private OssService ossService;
    @Resource
    private VideoMapper videoMapper;
    @Resource
    private ChapterMapper chapterMapper;
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private CourseCollectMapper courseCollectMapper;

    @Override
    public String saveCourseInfo(CourseInfoForm courseInfoForm) {
        // 保存课程
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        course.setStatus(Course.COURSE_DRAFT);
        this.save(course);
        // 保存课程详情
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.insert(courseDescription);

        return course.getId();
    }

    @Override
    public CourseInfoForm getCourseById(String id) {
        // 课程信息
        Course course = this.getById(id);
        if (course == null) {
            return null;
        }
        // 课程描述
        CourseDescription courseDescription = courseDescriptionMapper.selectById(id);

        CourseInfoForm courseInfoForm = new CourseInfoForm();
        BeanUtils.copyProperties(course, courseInfoForm);
        courseInfoForm.setDescription(courseDescription.getDescription());
        return courseInfoForm;
    }

    @Override
    public void updateCourse(CourseInfoForm courseInfoForm) {
        // 保存课程
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoForm, course);
        course.setStatus(Course.COURSE_DRAFT);
        this.updateById(course);
        // 保存课程详情
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseInfoForm.getDescription());
        courseDescription.setId(course.getId());
        courseDescriptionMapper.updateById(courseDescription);
    }

    @Override
    public PageUtils queryPage(Long currentPage, Long limit, CourseQueryVo queryVo) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();

        String title = queryVo.getTitle();
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like("a.title", title);
        }
        String subjectId = queryVo.getSubjectId();
        if (StringUtils.isNotBlank(subjectId)) {
            queryWrapper.eq("a.subject_id", subjectId);
        }
        String subjectParentId = queryVo.getSubjectParentId();
        if (StringUtils.isNotBlank(subjectParentId)) {
            queryWrapper.eq("a.subject_parent_id", subjectParentId);
        }
        String teacherId = queryVo.getTeacherId();
        if (StringUtils.isNotBlank(teacherId)) {
            queryWrapper.eq("a.teacher_id", teacherId);
        }
        queryWrapper.orderByDesc("gmtCreate");

        // 分页对象
        Page<CourseVo> courseVoPage = new Page<>(currentPage, limit);
        // 自定义分页查询
        List<CourseVo> pageList = baseMapper.selectCourseVoPage(courseVoPage, queryWrapper);
        courseVoPage.setRecords(pageList);

        return new PageUtils(courseVoPage);
    }

    /**
     * 发生所有异常都回滚
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeCourse(List<String> idList) {

        // 删除图片
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("cover").in("id", idList);
        List<Object> coverList = this.listObjs();
        List<String> filePaths = new ArrayList<>();
        // 获取文件的绝对路径，去掉前面的URL地址
        coverList.forEach(url ->{
            if (StringUtils.isNotBlank((String) url)) {
                filePaths.add(StringUtils.substringAfter((String) url, "com/"));
            }
        });
        // 调用OSS服务删除文件
        if (!filePaths.isEmpty()) {
            R res = ossService.deleteFiles(filePaths);
        }

        // 删除记录，先删除其关联的子表记录，再删除主表记录
        // 1. 删除课程描述
        courseDescriptionMapper.deleteBatchIds(idList);
        // 2. 删除课程video表
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.in("course_id", idList);
        videoMapper.delete(videoQueryWrapper);
        // 3. 删除课程评论表记录
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.in("course_id", idList);
        commentMapper.delete(commentQueryWrapper);
        // 4. 删除课程章节
        QueryWrapper<Chapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.in("course_id", idList);
        chapterMapper.delete(chapterQueryWrapper);
        // 5. 删除课程收藏表记录
        QueryWrapper<CourseCollect> courseCollectQueryWrapper = new QueryWrapper<>();
        courseCollectQueryWrapper.in("course_id", idList);
        courseCollectMapper.delete(courseCollectQueryWrapper);
        // 6. 最后删除主记录
        this.removeByIds(idList);
        return true;
    }

    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.id", id);
        return baseMapper.getCoursePublishVoById(id);
    }

    @Override
    public boolean publishCourseById(String id) {
        Course course = new Course();
        course.setStatus(Course.COURSE_NORMAL).setId(id);
        return this.updateById(course);
    }

    @Override
    public List<Course> webSelectList(WebCourseQueryVo webCourseQueryVo) {
        // 定义查询对象
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        //查询已发布的课程
        queryWrapper.eq("status", Course.COURSE_NORMAL);
        if (webCourseQueryVo != null) {
            String subjectId = webCourseQueryVo.getSubjectId();
            if (StringUtils.isNotBlank(subjectId)) {
                queryWrapper.eq("subject_id", subjectId);
            }
            String subjectParentId = webCourseQueryVo.getSubjectParentId();
            if (StringUtils.isNotBlank(subjectParentId)) {
                queryWrapper.eq("subject_parent_id", subjectParentId);
            }
            String buyCountSort = webCourseQueryVo.getBuyCountSort();
            if (StringUtils.isNotBlank(buyCountSort)) {
                // 销量降序
                queryWrapper.orderByDesc("buy_count");
            }
            String gmtCreateSort = webCourseQueryVo.getGmtCreateSort();
            if (StringUtils.isNotBlank(gmtCreateSort)) {
                // 创建时间降序
                queryWrapper.orderByDesc("gmt_create");
            }
            String priceSort = webCourseQueryVo.getPriceSort();
            if (StringUtils.isNotBlank(priceSort)) {
                // 价格降序
                queryWrapper.orderByDesc("price");
            }
        }
        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WebCourseVo selectWebCourseVoById(String courseId) {
        //更新课程浏览数
        Course course = baseMapper.selectById(courseId);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
        //获取课程信息
        return baseMapper.selectWebCourseVoById(courseId);
    }

    /**
     * 通过缓存注解，自动将数据库内容同步到redis，从redis中取数据
     */
    @Cacheable(value = "siteHome", key = "'hotCourse'")
    @Override
    public List<Course> selectHotCourse() {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("view_count");
        queryWrapper.last("limit 8");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public CourseDto getCourseDtoById(String courseId) {
        return baseMapper.getCourseDtoById(courseId);
    }
}
